package com.hxkj.config;

import com.hxkj.domain.po.Templet;
import com.hxkj.domain.po.WebsiteAddr;
import com.hxkj.service.TemplteService;
import com.hxkj.service.WebsiteAddrService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * @desc 初始化数据 把每个站点下的url配置放入redis缓存
 *
 * @author yaosy
 * @date 2018年8月14日
 * ***/
@Component
@Order(value=2)
@Slf4j
public class InitUrlDataConfig implements CommandLineRunner {

    @Override
    public void run(String... strings) throws Exception {
        insertWebSiteAddr();
        insertTemplte();
    }

    @Resource
    private WebsiteAddrService websiteAddrService;

    @Resource
    private TemplteService templteService;

    @Resource
    private RedisTemplate redisTemplate;

    private static final String WEBSITE_ADD = "WEBSITE_ADD";

    private static final String WEBSITE_PATH = "templet_";

    private static final String WEBSITE_SITE = "templet_";



    public void insertWebSiteAddr()throws Exception{
        WebsiteAddr website = new WebsiteAddr();
        website.setDelTag(0L);
        List<WebsiteAddr> websiteAddr = websiteAddrService.getList(website);
        if(websiteAddr!=null && websiteAddr.size() >0){
            Map map = new HashMap<>();
           for(WebsiteAddr wb : websiteAddr){
               setMap( WEBSITE_ADD+wb.getSiteId(),wb);
           }
        }
    }


    public void insertTemplte(){
        List<Templet>  templetList = templteService.getList();
        if(templetList!=null && templetList.size() >0){
            for(Templet t : templetList){
                setMap( WEBSITE_SITE+t.getSiteId()+"_"+t.getTempletId(),t);
                setMap( WEBSITE_PATH+t.getSiteId()+"_"+t.getPath(),t);
            }
        }
    }

    public <T> void setMap(String key, T obj){
        redisTemplate.opsForValue().set(key,obj);
    }

}
